//////////////////////////////////////////////
// main.js
//
// Main file for Electron based launch.
//////////////////////////////////////////////

/// Imports ----------------------------------

const {app, BrowserWindow, ipcMain} = require("electron") ;
const fs = require("fs") ;
const path = require("path") ;

/// Vars -------------------------------------

var IS_CI = false ;

/// Main -------------------------------------

// Disable warning triggered by the unsafe eval (required for wasm)
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = true ;

/// Callbacks --------------------------------

const createWindow = () =>
{
	const win = new BrowserWindow({
		width: 800,
		height: 600,
		webPreferences:
		{
			preload: path.join(__dirname, "WebUnitTests_pre.js")
		}
	})

	win.loadFile('index.html')
} ;

/// Events -----------------------------------

app.whenReady().then(() =>
{
	IS_CI = process.argv.includes("-ci") ;

	if (IS_CI)
		console.log("Running for CI...") ;

	createWindow() ;

	app.on('activate', () =>
	{
		if (BrowserWindow.getAllWindows().length === 0)
			createWindow() ;
	}) ;
}) ;

app.on('window-all-closed', () =>
{
	if (process.platform !== 'darwin')
		app.quit() ;
}) ;

/// Ipc --------------------------------------

ipcMain.handle("nk:isCi", () =>
{
	return IS_CI ;
}) ;

ipcMain.handle("nk:listTestFiles", () =>
{
	const inspectDir = (path) =>
	{
		// List what is in the Tests folder
		const files = fs.readdirSync(path) ;
		var result = [] ;
		
		while (files.length > 0)
		{
			// Pop entry
			const file = path + "/" + files.pop() ;
			const fileStats = fs.statSync(file) ;

			if (fileStats.isFile() && file.endsWith(".js"))
				result.push(file) ;
			else if (fileStats.isDirectory())
				result = result.concat(inspectDir(file)) ;
		}

		return result ;
	} ;

	return inspectDir("Tests") ;
}) ;

ipcMain.handle("nk:readFile", (event, filePath) =>
{
	return fs.readFileSync(path.join(__dirname, filePath)) ;
}) ;

ipcMain.handle("nk:writeFile", (event, path, content) =>
{
	fs.writeFile(path, content, err => {if (err) {console.log(err) ;}}) ;
}) ;

ipcMain.handle("nk:forwardException", (event, message) =>
{
	console.log("Unit test got an exception while running, preventing further work. Message :") ;
	console.log(message) ;
	console.log("Leaving run.")

	if (IS_CI)
		app.quit() ;
}) ;

ipcMain.handle("nk:closeApp", () =>
{
	app.quit() ;
}) ;